package cn.innosmart.aq.view.fragment;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.EmployeeAdapter;
import cn.innosmart.aq.application.AQApplication;
import cn.innosmart.aq.bean.Employee;
import cn.innosmart.aq.customize.InputDialog;
import cn.innosmart.aq.util.FragmentManagerTool;
import cn.innosmart.aq.util.INetworkInteractUtil;
import cn.innosmart.aq.util.NetworkInteractUtil;
import cn.innosmart.aq.util.SharedUtil;
import cn.innosmart.aq.util.SystemConstant;

public class AssignProviderFragment extends BaseFragment implements INetworkInteractUtil {
    InputDialog inputUidDialog;
    private NetworkInteractUtil networkInteractUtil;
    private Toolbar toolbar;
    private View.OnClickListener onNavigationClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getActivity().onBackPressed();
        }
    };

    private Menu menus;
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_clear:
                    clearCurrentProvider();
                    break;
                case R.id.action_edit:
                    showInputDialog();
                    break;
            }
            return true;
        }
    };
    private View.OnClickListener onDeleteClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        }
    };

    private void clearCurrentProvider() {
        JSONObject jsonParams = new JSONObject();
        JSONObject loginSp = SharedUtil.getInstance().readLoginInfo();
        String username = null;
        try {
            username = loginSp.getString("username");
            jsonParams.put("username", username);
            jsonParams.put("provider_id", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest clearRequest = new JsonObjectRequest(Request.Method.POST, "http://api.innosmart.cn:1337/account/update_service_provider", jsonParams,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        int resultCode = -1;
                        try {
                            resultCode = response.getInt("code");
                            if (resultCode == 0) {
                                ((TextView) getActivity().findViewById(R.id.provider_name)).setText("");
                                ((TextView) getActivity().findViewById(R.id.provider_tel)).setText("");
                                ((TextView) getActivity().findViewById(R.id.provider_address)).setText("");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> header = new HashMap<String, String>();
                header.put("Authorization", " Bearer " + SystemConstant.session_token);
                return header;
            }

            ;
        };
        AQApplication.getInstance().mQueue.add(clearRequest);
    }

    private void showInputDialog() {
        if (inputUidDialog == null) {
            inputUidDialog = new InputDialog(getActivity());
            inputUidDialog.setHint(getActivity().getString(R.string.provider_no));
            inputUidDialog.setTitle(getActivity().getString(R.string.assign_provider));
            final EditText etUserCount = (EditText) inputUidDialog.findViewById(R.id.et_name);
            InputFilter[] filters = {new InputFilter.LengthFilter(15)};
            etUserCount.setFilters(filters);
            inputUidDialog.setPositiveButton(getActivity().getString(R.string.sure), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final String providerNo = etUserCount.getText().toString().trim();
                    if (TextUtils.isEmpty(providerNo)) {
                        showToast(getActivity().getString(R.string.provider_can_not_empty));
                        return;
                    }

                    JSONObject jsonParams = new JSONObject();
                    JSONObject loginSp = SharedUtil.getInstance().readLoginInfo();
                    String username = null;
                    try {
                        username = loginSp.getString("username");
                        jsonParams.put("username", username);
                        jsonParams.put("provider_id", providerNo);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    JsonObjectRequest addEmployeeRequest = new JsonObjectRequest(Request.Method.POST, "http://api.innosmart.cn:1337/account/update_service_provider", jsonParams,
                            new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    int resultCode = -1;
                                    try {
                                        resultCode = response.getInt("code");
                                        System.out.println("update_service_provider code:" + resultCode);
                                        if (resultCode == 1) {
                                            Toast.makeText(getActivity(), R.string.no_provider_like_this, Toast.LENGTH_LONG).show();
                                        }
                                        getData();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    inputUidDialog.dismiss();
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            inputUidDialog.dismiss();
                        }
                    }) {
                        @Override
                        public Map<String, String> getHeaders() throws AuthFailureError {
                            HashMap<String, String> header = new HashMap<String, String>();
                            header.put("Authorization", " Bearer " + SystemConstant.session_token);
                            return header;
                        }

                        ;
                    };
                    AQApplication.getInstance().mQueue.add(addEmployeeRequest);
                }
            });
            inputUidDialog.setNegativeButton(getActivity().getString(R.string.cancel), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    inputUidDialog.dismiss();
                }
            });
        } else {
            EditText etUserCount = (EditText) inputUidDialog.findViewById(R.id.et_name);
            etUserCount.setText("");
        }
        inputUidDialog.show();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        return inflater.inflate(R.layout.fragment_assign_provider, null);
    }

    private void setBar() {
        toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
        ((ImageView) getActivity().findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        toolbar.setTitle("");
        ((TextView) getActivity().findViewById(R.id.tv_toolbar)).setText(getString(R.string.assign_provider));
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
        getActivity().findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });
        toolbar.setOnMenuItemClickListener(onMenuItemClick);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setBar();
        getData();
        networkInteractUtil = new NetworkInteractUtil(this);
    }

    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.menu_assign_provider, menu);
        menus = menu;
        super.onCreateOptionsMenu(menu, inflater);
    }

    private void getData() {
        JSONObject loginSp = SharedUtil.getInstance().readLoginInfo();
        String username = null;
        try {
            username = loginSp.getString("username");
            String url = "http://api.innosmart.cn:1337/account/find?where={\"username\":\"" + username + "\"}";
            System.out.println(url);
            JsonArrayRequest jsonStatementUrl = new JsonArrayRequest(url,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {
                            try {
                                JSONObject provider = response.getJSONObject(0).getJSONObject("provider");
                                ((TextView) getActivity().findViewById(R.id.provider_name)).setText(provider.getString("name"));
                                ((TextView) getActivity().findViewById(R.id.provider_tel)).setText(provider.getString("phone"));
                                ((TextView) getActivity().findViewById(R.id.provider_address)).setText(provider.getString("address"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            Log.d("TAG", response.toString());
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.e("TAG", error.getMessage(), error);
                        }
                    });
            AQApplication.getInstance().mQueue.add(jsonStatementUrl);
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void onNetworkInteractAllOver(int ret) {

    }

    @Override
    public void onNetworkInteractOver(int ret, String flag, Object object) {
    }

    @Override
    public void onResume() {
        super.onResume();
        toolbar.setNavigationIcon(null);
    }
}
